<?php

/*
 * To change this license header, choose License Headers in Project Properties.
 * To change this template file, choose Tools | Templates
 * and open the template in the editor.
 */

/**
 * Description of UserLoginModel
 *
 * @author John
 */
namespace Admin\Model;
use Think\Model;
use Org\Util\Rbac;

class UserLoginModel extends Model{
    protected $patchValidate = true;
    protected $autoCheckFields = false;
    
    protected $_auto = array(
        
    );
    
    protected $_validate = array(
        array("username","require","用户名必须填写"),
        array("password","require","密码必须填写"),
        array("code","checkCode","验证码错误",1,'callback'),
    );
    
    protected function checkCode(){
        $code = I("post.code");
        if(!$code){
            return false;
        }
        $verify = new \Think\Verify();
        return $verify->check($code);
    }
    
    public function login($username,$password){
        //生成认证条件
        $check_map = array();
        $check_map['user_name'] = $username;
        $check_map['is_active'] = 1;
        
        $authInfo = Rbac::authenticate($check_map);
            
        if(false == $authInfo){
           // $this->error("账号不存在或禁用！");
            $data['sign']="账号不存在或禁用！";
            $data['status']=0;
            return $data;
        }else{
            if($authInfo['password'] != $password){
                $data['sign']="密码错误！";
                $data['status']=0;
                return $data;
            }
            session(C("USER_AUTH_KEY"),$authInfo['id']);
            session(['loginUserName'],$authInfo['user_name']);
            if($authInfo['user_name']=="Administrator"){
                session(C('ADMIN_AUTH_KEY'),true);
            }
            $user_db = M("User");
            $data = array();
            $data['id'] = $authInfo['id'];
            $data['last_login'] = time();
            $data['last_ip'] = get_client_ip();
            $user_db->save($data);

            Rbac::saveAccessList();
            
            $ret_data = array();
            $ret_data['sign']="登录成功！";
            $ret_data['status']=1;
            return $ret_data;
        }
    }
}
